package com.zhouchao.gateway.filter;

import com.zhouchao.gateway.feign.user.UserServiceFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * @Author: zhouchao
 * @Date: 2021/10/22 21:28
 * @Description:
 */
@Slf4j
@Component
public class CheckTokenFilter implements GlobalFilter, Ordered {
    private static final List<String> FILTER_LIST = Arrays.asList("/api/user","/api/code");

    @Autowired
    private UserServiceFeignClient userServiceFeignClient;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String path = request.getURI().getPath();

        boolean flag = true;
        for (String uri : FILTER_LIST) {
            if (path.startsWith(uri)){
                flag = false;
                break;
            }
        }

        boolean result = true;
        if (flag){
            List<HttpCookie> tokenList = request.getCookies().get("token");
            if (CollectionUtils.isEmpty(tokenList)){
                result = false;
            }else{
                HttpCookie httpCookie = tokenList.get(0);
                String token = httpCookie.getValue();
                String email = userServiceFeignClient.getInfo(token);
                if (StringUtils.isEmpty(email)){
                    result = false;
                }
            }
        }

        if (!result){
            response.setStatusCode(HttpStatus.FORBIDDEN);
            log.debug("token验证未通过");
            String data = "token error";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
